package org.example.demo.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.demo.constant.Constants;
import org.example.demo.model.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //true表示放行,false表示拦截
        log.info("LoginInterceptor preHandle...");
        //获取session,并且判断session中存储的userinfo信息是否为空
        HttpSession session = request.getSession();  //默认true .如果没有的话不要拿session
        //从session中获取用户信息
        //如果用户信息为空,说明用户未登录,就跳转到登录界面
        UserInfo userInfo =(UserInfo) session.getAttribute(Constants.USER_SESSION_KEY);  //通过session得到用户登录的信息
        if(userInfo == null  || userInfo.getId() < 0) {
            //用户未登录
            response.setStatus(401);
            return false;
        }

        return true;
    }

}
